package com.chalmers.irc2you;

import java.util.LinkedList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.chalmers.irc2you.model.DataHandler;
import com.chalmers.irc2you.model.Message;
import com.chalmers.irc2you.network.Connection;

public class ChannelTab extends Activity {

	private LinearLayout messageLayout;
	private DataHandler dh;
	private SharedPreferences pref;
	private Handler updateHandler;
	private OnClickListener updateListener;
	private Runnable runUpdate;

	public void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.channeltab);
		dh = DataHandler.getInstance(getApplicationContext());
		pref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		runUpdate = new Runnable() {

			@Override
			public void run() {
				updateChannel();
			}
		};

		updateHandler = new Handler();
		updateListener = new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				updateHandler.removeCallbacks(runUpdate);
				updateHandler.postDelayed(runUpdate, 5000L);
			}
		};

		updateListener.onClick(findViewById(R.id.messageLayout));

		Button button = (Button) findViewById(R.id.mainSendButton);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Connection.sendMessage(dh.getCurrentChannel(),
						((EditText) findViewById(R.id.channelTextEditor))
								.getText().toString());
			}
		});
	}

	private void updateChannel() {
		if (dh.updateChannel(Connection.getChannelUpdates(dh
				.getCurrentChannel()))) {
			messageLayout = (LinearLayout) findViewById(R.id.messageLayout);

			LinkedList<Message> tempChannel = dh.getChannel(
					dh.getCurrentChannel()).getMessages();
			for (int i = 0; i < tempChannel.size(); i++) {
				messageLayout.addView(new MessageView(getApplicationContext(),
						tempChannel.get(i).getTimeStamp(), tempChannel.get(i)
								.getSender(), tempChannel.get(i).getMessage()));
			}

		}
	}

	public void onResume() {
		super.onResume();

	}

	public void onPause() {
		super.onPause();

	}

	public void onDestroy() {
		super.onDestroy();

	}
}
